package com.bjsxt.comment.dao.impl;

import com.bjsxt.comment.dao.CommentDao;
import com.bjsxt.livegoods.pojo.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.Map;

/**
 * @ClassName : CommentDaoImpl
 * @Description :
 * @Author : ZWZ
 * @Date: 2021/8/26 10:45
 */
@Repository
public class CommentDaoImpl implements CommentDao {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public List<Comment> findCommentsByPage(Query query) {
        return mongoTemplate.find(query, Comment.class);
    }

    @Override
    public long countByQuery(final String itemId) {
        // 创建聚合查询条件
        TypedAggregation<Comment> commentTypedAggregation = new TypedAggregation<>(
                Comment.class,
                Aggregation.group("itemId").count().as("count")
        );
        AggregationResults<Map> result = mongoTemplate.aggregate(commentTypedAggregation, Map.class);
        List<Map> mappedResults = result.getMappedResults();
        for (Map map : mappedResults) {
            if (map.get("_id").equals(itemId)) {
                return Long.parseLong(map.get("count").toString());
            }
        }
        return 0L;
    }

    @Override
    public void save(Comment comment) {
        mongoTemplate.save(comment);
    }
}
